<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="教练姓名" prop="coachName">
        <el-input
          v-model="queryParams.coachName"
          placeholder="请输入教练姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教练工号" prop="coachCode">
        <el-input
          v-model="queryParams.coachCode"
          placeholder="请输入教练工号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教练性别" prop="coachGender">
        <el-select v-model="queryParams.coachGender" placeholder="请选择教练性别" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="教练状态" prop="coachStatus">
        <el-select v-model="queryParams.coachStatus" placeholder="请选择教练状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.coach_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bussiness:coach:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bussiness:coach:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bussiness:coach:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bussiness:coach:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="coachList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="教练姓名" align="center" prop="coachName" />
      <el-table-column label="教练工号" align="center" prop="coachCode" />
      <el-table-column label="教龄" align="center" prop="coachTeachYear" />
      <el-table-column label="教练性别" align="center" prop="coachGender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.coachGender"/>
        </template>
      </el-table-column>
      <el-table-column label="出生日期" align="center" prop="coachBirthday" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.coachBirthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客单价" align="center" prop="coachUnitPrice" />
      <el-table-column label="教练介绍" align="center" prop="coachDescription" show-overflow-tooltip />
      <el-table-column label="教练状态" align="center" prop="coachStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.coach_status" :value="scope.row.coachStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleHire(scope.row)"
            v-hasPermi="['bussiness:coach:hire']"
          >雇佣</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bussiness:coach:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bussiness:coach:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教练信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="教练姓名" prop="coachName">
          <el-input v-model="form.coachName" placeholder="请输入教练姓名" />
        </el-form-item>
        <el-form-item label="教练工号" prop="coachCode">
          <el-input v-model="form.coachCode" placeholder="请输入教练工号" />
        </el-form-item>
        <el-form-item label="教龄" prop="coachTeachYear">
          <el-input v-model.number="form.coachTeachYear" placeholder="请输入教龄" />
        </el-form-item>
        <el-form-item label="教练性别" prop="coachGender">
          <el-select v-model="form.coachGender" placeholder="请选择教练性别">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
:value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="coachBirthday">
          <el-date-picker clearable size="small"
            v-model="form.coachBirthday"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择教练出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客单价" prop="coachUnitPrice">
          <el-input v-model.number="form.coachUnitPrice" placeholder="请输入客单价" />
        </el-form-item>
        <el-form-item label="教练介绍" prop="coachDescription">
          <el-input v-model="form.coachDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="教练状态" prop="coachStatus">
          <el-select v-model="form.coachStatus" placeholder="请选择教练状态">
            <el-option
              v-for="dict in dict.type.coach_status"
              :key="dict.value"
              :label="dict.label"
:value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加雇佣　对话框 -->
    <el-dialog :title="hire.title" :visible.sync="hire.open" width="500px" append-to-body>
      <el-form ref="hireForm" :model="hire.form" :rules="hireRules" label-width="80px">
        <el-form-item label="当前日期">
          <template>
            <span>{{ parseTime(hire.form.currentDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-form-item>
        <el-form-item label="雇佣时间" prop="time">
          <el-time-select
            placeholder="雇佣起始时间"
            v-model="hire.form.startTime"
            :picker-options="{
              start: pickerStartTime,
              step: '00:15',
              end: pickerEndTime
            }">
          </el-time-select> ~ 
          <el-time-select
            placeholder="雇佣结束时间"
            v-model="hire.form.endTime"
            :picker-options="{
              start: purchaseEndTime,
              step: '00:15',
              end: pickerEndTime
            }">
          </el-time-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitHireForm">确 定</el-button>
        <el-button @click="cancelHire">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCoach, getCoach, delCoach, addCoach, updateCoach } from "@/api/bussiness/coach";
import { addHire } from "@/api/bussiness/hire";

export default {
  name: "Coach",
  dicts: ['sys_user_sex', 'coach_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教练信息表格数据
      coachList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        coachName: null,
        coachCode: null,
        coachGender: null,
        coachStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        coachName: [
          { required: true, message: '请输入教练姓名', blur: 'change' }
        ],
        coachCode: [
          { required: true, message: '请输入教练工号', blur: 'change' }
        ],
        coachTeachYear: [
          { required: true, type: 'number', message: '请输入教龄', blur: 'change' }
        ],
        coachUnitPrice: [
          { required: true, type: 'number', message: '请输入客单价', blur: 'change' }
        ],
        coachGender: [
          { required: true, message: '请选择教练性别', blur: 'change' }
        ]
      },
      /** 雇佣弹窗相关参数 */
      hire: {
        open: false,
        title: '请选择雇佣时间',
        form: {
          currentDate: '',
          startTime: '',
          endTime: ''
        }
      },
      hireRules: {

      },
      // 预约时间 开始时间
      pickerStartTime: '08:00',
      // 预约时间 截至时间
      pickerEndTime: '21:00',
      // 可选日期空间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24*60*60*1000;
        }
      },
      // 定时任务
      timer: '',
      // 当前点击行信息
      currentHireRow: {}
    };
  },
  created() {
    this.getList();
  },
  mounted(){
    this.timer = setInterval(()=> {this.getPickerStartTime()}, 30000)
  },
  beforeDestroy(){
    clearInterval(this.timer)
  },
  computed: {
    purchaseEndTime: function (){
      this.hire.form.endTime = ''
      if(this.hire.form.startTime){
        let time = this.hire.form.startTime.split(':')
        let tmp_hour = time[0] / 1 + 1
        let tmp_min = time[1] / 1
        // 判断是否超过结束时间
        let endT = this.pickerEndTime.split(':')
        if(tmp_hour >= endT[0]){
          tmp_hour = endT[0]
          tmp_min = endT[1]
        }
        return (tmp_hour < 10 ? '0' + tmp_hour : tmp_hour) + ':' + (tmp_min == 0? '00' : tmp_min)
      }
    }
  },
  methods: {
    // 获取可选开始时间
    getPickerStartTime(){
      // 如果预约日期是今天，做处理。
      let dt = this.hire.form.currentDate
      if(dt){
        let ndt = new Date()
         if(dt.getFullYear() == ndt.getFullYear() && dt.getMonth() == ndt.getMonth() && dt.getDate() == ndt.getDate()){
            let hh = new Date().getHours()
            let mm = new Date().getMinutes()
            let tmp_hh, tmp_mm
            tmp_hh = hh
            // 如果分钟大于45，小时+1
            if(mm < 15){
              tmp_mm = '15'
            }else if( 15 < mm && mm < 30){
              tmp_mm = '30'
            }else if( 30 < mm && mm < 45){
              tmp_mm = '45'
            }else if( mm >= 45){
              tmp_mm = '00'
              tmp_hh = hh + 1
            }
            console.log(tmp_hh + ":" + tmp_mm)
            if(tmp_hh < 8){
              return this.pickerStartTime = '08:00'
            }
            return this.pickerStartTime = tmp_hh + ":" + tmp_mm
         }
      }
      return this.pickerStartTime = '08:00'
    },
    /** 查询教练信息列表 */
    getList() {
      this.loading = true;
      listCoach(this.queryParams).then(response => {
        this.coachList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        coachId: null,
        coachName: null,
        coachCode: null,
        coachTeachYear: null,
        coachGender: null,
        coachBirthday: null,
        coachUnitPrice: null,
        coachDescription: null,
        coachStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.coachId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教练信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const coachId = row.coachId || this.ids
      getCoach(coachId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改教练信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.coachId != null) {
            updateCoach(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoach(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const coachIds = row.coachId || this.ids;
      this.$modal.confirm('是否确认删除教练信息编号为"' + coachIds + '"的数据项？').then(function() {
        return delCoach(coachIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bussiness/coach/export', {
        ...this.queryParams
      }, `coach_${new Date().getTime()}.xlsx`)
    },
    /** 处理雇佣按钮 */
    handleHire(row){
      // 判断教练状态
      if(row.coachStatus != 'free'){
        return this.$modal.msgError("当前教练正在授课，请更换其他教练！");
      }
      // 制空对象
      this.$set(this.hire, 'form', {
        currentDate: '',
        startTime: '',
        endTime: ''
      })
      this.hire.form.currentDate = new Date()
      this.currentHireRow = row
      this.getPickerStartTime()
      // 打开弹窗
      this.hire.open = true
    },
    /** 雇佣弹窗确认按钮处理 */
    submitHireForm(){
      // 1. 判空
      let tmp_currentDate = this.hire.form.currentDate
      if(!tmp_currentDate){
        return this.$modal.msgError("当前日期获取失败！请刷新页面！");
      }
      let {startTime, endTime} = this.hire.form
      if(!startTime){
        return this.$modal.msgError("请选择雇佣开始时间！");
      }
      if(!endTime){
        return this.$modal.msgError("请选择雇佣结束时间！");
      }
      tmp_currentDate = this.parseTime(tmp_currentDate, '{y}-{m}-{d}')
      let tmp_startTime = new Date(tmp_currentDate + ' ' + startTime + ':00');
      let tmp_endTime = new Date(tmp_currentDate + ' ' +endTime+ ':00');
      console.log('1', tmp_endTime.getTime() - tmp_startTime.getTime())
      if(tmp_endTime.getTime() - tmp_startTime.getTime() < 3600000){
        return this.$modal.msgError("雇佣时间最少为1个小时，请重新选择雇佣起止时间！");
      }

      // 2.调用接口
      let date = this.hire.form.currentDate
      let comDate = date.getFullYear() + '-' 
          + ((date.getMonth() + 1) < 10 ? '0'+ (date.getMonth() + 1) : date.getMonth() + 1) + '-' 
          + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
      let hireStartTime = comDate + ' ' + startTime + ':00'
      let hireEndTime = comDate + ' ' + endTime + ':00'
      console.log(hireStartTime, hireEndTime)
      let {coachId} = this.currentHireRow
      let params = {
        hireStartTime,
        hireEndTime,
        coachId
      }
      addHire(params).then(res=>{
        this.$modal.msgSuccess("雇佣成功！");
        this.hire.open = false;
        this.getList();
      })
    },
    cancelHire(){
      this.hire.open = false
    }
  }
};
</script>
